var sysT = require('../../../../tool/sys-tool.js')
var businessT = require('../../../../tool/business-tool.js')
var businessType = require('../../../../public/business-type.js')
var p = require('../../public/model/public.js')
var publicData = require('../../../../constant/data.js')
var url = require('../../../../constant/url.js')
import Net from '../../../../tool/net.js'
var net = new Net()
var pay = require('../../../../public/pay.js')
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    adapter: {
      suffix: ''
    },
    head: [],
    list: {},
    total: 0,
    pay: {
      i: '', 
      d: ''
    },
    discount: {
      count: 0,
      fee: 0,
      status: '未使用'
    },
    discountId:''
  },

  refreshDiscount: function (dis) {
    this.data.discount.fee = dis.fee
    this.data.discountId = dis.ids
    if (this.data.discount.fee > 0) {
      this.data.discount.status = '-¥' + this.data.discount.fee.toFixed(2)
    } else {
      this.data.discount.status = '未使用'
    }
    var order = app.purchase.order
    var pay = (order.totalFee.total_fee - this.data.discount.fee).toFixed(2)
    this.data.pay = {
      i: pay.slice(0, -2),
      d: pay.slice(-2)
    }
    this.setData({
      discount: this.data.discount,
      pay: this.data.pay
    })
  },

  payLaterAction: businessT.action(function (sender) {
    wx.showLoading({
      title: '正在提交订单',
      mask: true
    })
    var order = app.purchase.order
    var obj = this.getParameters({
      pay_channel: 5,
      fund: order.payFor == businessType.PurchasePayFor.socialInsurance ? 0 : order.accumulationFund,
      pay_for: order.payFor
    })
    var path = order.isSupplementaryPay ? url.createLaterSupplementaryPayOrder : url.createPayLaterOrder
    net.connectNeedLogin({
      url: url.app_host + path,
      data: obj,
      success: (err, res) => {
        wx.hideLoading()
        var pages = getCurrentPages()
        businessT.debugLog(pages)
        pages[0].route('../../page/mine/pages/wait-for-pay/wait-for-pay')
      },
      fail: (err, res) => {
        wx.hideLoading()
        businessT.showFailTips(err, '提交订单失败')
      }
    })

  }),

  payAction: businessT.action(function (sender) {
    wx.showToast({
      title: '暂时无法提交订单',
      icon:'none'
    })
    return
    wx.showLoading({
      title: '正在提交订单',
      mask: true
    })
    
    var that = this
    pay.prepay({
      success: e => {
        var order = app.purchase.order
        if (order.purchaseType == businessType.PurchaseType.socialInsurance) {
          this.createSocialInsuranceOrder(businessType.ResultServeyType.resultServeyTypeSB)
        } else if (order.purchaseType == businessType.PurchaseType.socialInsurancePackage) {
          this.createSocialInsuranceOrder(businessType.ResultServeyType.resultServeyTypePack)
        } else if (order.purchaseType == businessType.PurchaseType.accumulationFund) {
          this.createAccumulationFundOrder(businessType.ResultServeyType.resultServeyTypeAF)
        } else if (order.purchaseType == businessType.PurchaseType.accumulationFundPackage) {
          this.createAccumulationFundOrder(businessType.ResultServeyType.resultServeyTypePack)
        }
      },
      fail: e => {
        wx.hideLoading()
        businessT.showFailTips(e, '提交订单暂时无法使用')
      }
    })
  }),

  createSocialInsuranceOrder: function (type) {
    var order = app.purchase.order
    var obj = this.getParameters({
      pay_channel: 5,
      fund: order.pack ? order.accumulationFund : 0,
      couponuser_id: this.data.discountId
    })
    var path = order.isSupplementaryPay ? url.createShebaoSupplementaryPayOrder : url.createShebaoOrder
    var that = this
    net.connectNeedLogin({
      url: url.app_host + path,
      data: obj,
      success: (err, res) => {
        pay.wxPay({
          data: res.data,
          success: e => {
            if (order.isNeedSalary) {
              that.checkSurvey(true, type)
            } else {
              that.checkSurvey(false, type)
            }
          },
          fail: e => {
            wx.hideLoading()
            businessT.showFailTips(err, '提交订单失败')
          }
        })
        
      },
      fail: (err, res) => {
        wx.hideLoading()
        businessT.showFailTips(err, '提交订单失败')
      }
    }, true)
  },

  createAccumulationFundOrder: function (type) {
    var order = app.purchase.order
    var obj = this.getParameters({
      pay_channel: 5,
      buyShebao: order.pack ? 1 : 0,
      fund: order.accumulationFund,
      couponuser_id: this.data.discountId
    })
    var path = order.isSupplementaryPay ? url.createFundSupplementaryPayOrder : url.createFundOrder
    var that = this
    net.connectNeedLogin({
      url: url.app_host + path,
      data: obj,
      success: (err, res) => {
        pay.wxPay({
          data: res.data,
          success: e => {
            if (order.isNeedSalary) {
              that.checkSurvey(true, type)
            } else {
              that.checkSurvey(false, type)
            }
          },
          fail: e => {
            wx.hideLoading()
            businessT.showFailTips(err, '提交订单失败')
          }
        })
      },
      fail: (err, res) => {
        wx.hideLoading()
        businessT.showFailTips(err, '提交订单失败')
      }
    }, true)
  },

  checkSurvey: function (isNeedSalary, type) {
    var pages = getCurrentPages() 
    if (isNeedSalary) {
      pages[0].route('../../public/pages/pay-success/pay-success?type=salary')
      return
    } else {
      net.connectNeedLogin({
        url: url.app_host + url.checkSurvey,
        data: {},
        success: (err, res) => {
          wx.hideLoading()
          if (res.data) {
            pages[0].route('../../public/pages/pay-success/pay-success?type=survey&surveyType=' + type)
          } else {
            this.queryPayPriceDifference()
          }
        },
        fail: (err, res) => {
          wx.hideLoading()
          pages[0].route('../../public/pages/pay-success/pay-success?type=share')
        }
      }, false)
    }   
  },

  queryPayPriceDifference: function() {
    var pages = getCurrentPages() 
    net.connectNeedLogin({
      url: url.app_host + url.queryPayPriceDifference,
      data: {},
      success: (err, res) => {
        wx.hideLoading()
        if (res.data > 0) {
          pages[0].route('../../public/pages/pay-success/pay-success?type=pay')
        } else {
          pages[0].route('../../public/pages/pay-success/pay-success?type=share')
        }
      },
      fail: (err, res) => {
        wx.hideLoading()
        pages[0].route('../../public/pages/pay-success/pay-success?type=share')
      }
    }, true)
  },

  getParameters: function (par) {
    var order = app.purchase.order
    var np = {
      sbuId: order.customerData.sbuId,
      cid: order.id,
      shebao_card: order.SSCard,
      hukou_type: order.accountType,
      month: businessT.changeTimeToNumber(order.beginTime),
      nums: order.timeInterval,
      first_sb: order.isFirstBuyShebao ? 1 : 0,
      first_fund: order.isFirstBuyFund ? 1 : 0,
      sb_wage: (order.isNeedSalary && !order.isInOffice) ? order.salary : 0,
      working: order.isNeedSalary ? (order.isInOffice ? 1 : 0) : 0
    }
    businessT.debugLog(order)
    businessT.debugLog(np)
    for (var key in par) {
      np[key] = par[key]
    }
    return np
  },

  discountChoose: businessT.action(function (sender) {
    wx.navigateTo({
      url: '../../../../public/pages/discount-view/discount-view?type=choose',
    })
  }),

  setUp: function () {
    var order = app.purchase.order
    //head
    var time = order.beginTime
    if (order.timeInterval > 1) {
      if (order.beginTime.slice(0, 4) == order.endTime.slice(0, 4)) {
        time = order.beginTime + '-' + order.endTime.slice(5, 8)
      } else {
        time = order.beginTime + '-' + order.endTime
      }
    }
    var se = order.customerData.user_name + '  ' + order.customerData.id_card + '\n' + order.cityName + '／' + publicData.accounts[order.accountType - 1]
    this.data.head = [time, se]

    //list
    var l = '购买时长'
    var r = order.timeInterval + '个月'
    if (order.totalFee.shebao) {
      l = l + '\n社保费'
      r = r + '\n¥ ' + Number(order.totalFee.shebao).toFixed(2)
    }
    if (order.totalFee.fund) {
      l = l + '\n公积金费用'
      r = r + '\n¥ ' + Number(order.totalFee.fund).toFixed(2)
    }
    if (order.totalFee.card_charge) {
      l = l + '\n社保卡'
      r = r + '\n¥ ' + Number(order.totalFee.card_charge).toFixed(2) + '/一次性'
    }

    l = l + '\n服务费'
    r = r + '\n¥ ' + Number(order.totalFee.s_charge + order.totalFee.f_charge).toFixed(2)
    this.data.list = {l: l, r: r}

    this.data.total = order.totalFee.total_fee.toFixed(2)

    var pay = (order.totalFee.total_fee - this.data.discount.fee).toFixed(2)
    this.data.pay = {
      i: pay.slice(0, -2),
      d: pay.slice(-2)
    }
  },

  getDiscountCount: function () {
    net.connectNeedLogin({
      url: url.app_host + url.getCashCouponCount,
      data: {
        phone: app.globalData.userInfo.phone
      },
      success: (err, res) => {
        this.data.discount.count = res.data.total
        if (this.data.discount.count == 0) {
          this.data.discount.status = '暂无优惠券'
        }
        this.setData({
          discount: this.data.discount
        })
      }
    }, true)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.adapter = {
      suffix: sysT.suffixOfClass()
    }

    this.setUp()

    this.setData({
      adapter: this.data.adapter,
      head: this.data.head,
      list: this.data.list,
      total: this.data.total,
      pay: this.data.pay
    })

    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getDiscountCount()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {
  
  // }
})